<template>
  <div class="app">
    <!-- <HeaderComp :title="userInfo.regStatus == 4 ? '资料修改' : '商户入网'"
    class="head-top" />-->
    <div class="header-box">
      <van-icon name="arrow-left" size="24" @click="goBack" />
      <div class="header-item">
        {{ userInfo.regStatus == 4 ? "资料修改" : "商户入网" }}
      </div>
      <!-- <van-icon name="arrow-left"
                size="24"
      style="visibility: hidden;" />-->
      <span class="header-save" @click="noSave">保存</span>
    </div>
    <div class="conten">
      <Remarks v-if="userInfo.regStatus == 4" :contents="userInfo.remarks" />

      <!-- 步骤条 -->
      <div>
        <Steps
          v-if="formData.openType == 1"
          :dataSource="[
            { name: '1基本信息', checked: true },
            { name: '2附件信息', checked: true },
          ]"
        />
        <Steps
          v-else
          :dataSource="[
            { name: '1基本信息', checked: true },
            { name: '2结算信息', checked: true },
            { name: '3费率信息', checked: true },
            { name: '4附件信息', checked: true },
          ]"
        />
      </div>

      <div class="attach-item">
        <p class="attach-item-title">营业场所</p>
        <div class="upload-content">
          <div class="attach-label">
            <p>请上传营业场所内景照</p>
            <p class="example" @click="lookExample(storeAddrImgExample)">
              查看示例&nbsp;
              <van-icon name="arrow" />
            </p>
          </div>
          <van-uploader
            :after-read="uploadStoreAddressImg"
            :before-delete="deleteStoreAddressImg"
            v-model="storeAddressImgList"
            :max-count="1"
            @oversize="onOversize"
          >
            <img src="../../assets/store/store-addr-img.png" alt />
          </van-uploader>
        </div>
      </div>
      <div class="attach-item">
        <p class="attach-item-title">门头照</p>
        <div class="upload-content">
          <div class="attach-label">
            <p>请上传营业场所门头照</p>
            <p class="example" @click="lookExample(doorImgExample)">
              查看示例&nbsp;
              <van-icon name="arrow" />
            </p>
          </div>
          <van-uploader
            :after-read="uploadStoreDoorImg"
            :before-delete="deleteStoreDoorImg"
            v-model="storeDoorImgList"
            :max-count="1"
            @oversize="onOversize"
          >
            <img src="../../assets/store/door-img.png" alt />
          </van-uploader>
        </div>
      </div>
      <div class="attach-item">
        <p class="attach-item-title">收银台</p>
        <div class="upload-content">
          <div class="attach-label">
            <p>请上传收银台</p>
            <p class="example" @click="lookExample(cashierExample)">
              查看示例&nbsp;
              <van-icon name="arrow" />
            </p>
          </div>
          <van-uploader
            :after-read="uploadCashierImg"
            :before-delete="deleteCashierImg"
            v-model="cashierImgList"
            :max-count="1"
            @oversize="onOversize"
          >
            <img src="../../assets/store/cashier-img.png" alt />
          </van-uploader>
        </div>
      </div>
      <div
        class="attach-item"
        v-if="
          $store.state.settlement.acconutType == 3 && formData.openType != 1
        "
      >
        <p class="attach-item-title">商户关系证明</p>
        <div class="upload-content">
          <div class="attach-label">
            <p>请上传关系证明材料</p>
            <p class="example" @click="lookExample(proofImgExample)">
              查看示例&nbsp;
              <van-icon name="arrow" />
            </p>
            <p class="example" @click="downloadExample">
              下载模板&nbsp;
              <van-icon name="arrow" />
            </p>
          </div>
          <van-uploader
            :after-read="uploadProofImg"
            :before-delete="deleteProofImg"
            v-model="proofImgList"
            :max-count="1"
            @oversize="onOversize"
          >
            <img src="../../assets/store/proof-img.png" alt />
          </van-uploader>
        </div>
      </div>
      <div
        class="attach-item"
        v-if="
          (merchantForm.merchantType === '1' ||
            merchantForm.merchantType === '2') &&
          settlement.acconutType === '3' &&
          merchantForm.defaultChannelCode === 'HAIKE'
        "
      >
        <p class="attach-item-title">法人手持商户关系证明</p>
        <div class="upload-content">
          <div class="attach-label">
            <p>请上传法人手持商户关系证明</p>
            <p class="example" @click="lookExample(cashierExample)">
              查看示例&nbsp;
              <van-icon name="arrow" />
            </p>
          </div>
          <van-uploader
            :after-read="uploadProofHandImg"
            :before-delete="deleteProofHandImg"
            v-model="proofHandImgList"
            :max-count="1"
            @oversize="onOversize"
          >
            <img src="../../assets/store/cashier-img.png" alt />
          </van-uploader>
        </div>
      </div>

      <div class="attach-item">
        <p class="attach-item-title">辅助材料（非必填）</p>
        <div class="upload-content">
          <div class="attach-label">
            <p>
              可上传辅助材料增加审 核成功率。例如：负责 人与门头合照、手持身
              份证等照片。
            </p>
          </div>
          <!--     :multiple="true" -->
          <van-uploader
            :after-read="uploadAssistImg"
            :before-delete="deleteAssistImg"
            v-model="assistImgList"
            :max-count="5"
            multiple="true"
            @oversize="onOversize"
          >
            <img src="../../assets/store/assist-img.png" alt />
          </van-uploader>
        </div>
      </div>
    </div>
    <van-dialog
      v-model="showExample"
      :title="
        merchantForm.channelCode === 'WX'
          ? '请参照下图打印一份结算证明函：'
          : '查看示例'
      "
      :message="getMessage"
      confirmButtonText="关闭"
      confirmButtonColor="#FFB72F"
    >
      <img :src="exampleImg" class="example-img" />
    </van-dialog>
    <van-button
      block
      type="info"
      color="#FFB72F"
      :disabled="pass"
      @click="nextStep"
      class="next-step-btn"
      >下一步</van-button
    >
  </div>
</template>

<script>
import storeAddrImgExample from "../../assets/store/store-addr-img-example.png";
import cashierExample from "../../assets/store/cashier-img-example.png";
import doorImgExample from "../../assets/store/door-img-example.png";
import proofImgExample from "../../assets/store/proof-img-example.png";
import { uploadImg } from "@/api/upload";
import { imgPreview, savePicture } from "@/utils/utils.js";
import { save } from "@/api/stores";

import { isBlacklist } from "@/api/merchant";
import { getChannelTemplate } from "@/api/channel";

export default {
  name: "Step4",
  components: {
    HeaderComp: () => import("@/components/HeaderComps"),
    Remarks: () => import("@/components/Remarks"),
    Steps: () => import("@/components/steps"),
  },
  data() {
    return {
      proofImgExample,
      storeAddrImgExample,
      doorImgExample,
      cashierExample,
      exampleImg: "",
      showExample: false,
      storeAddressImgList: [],
      cashierImgList: [],
      proofHandImgList: [],
      storeDoorImgList: [],
      proofImgList: [],
      assistImgList: [],
      formData: {},
      templateUrl: "",
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo;
    },
    merchantForm() {
      return this.$store.state.merchant;
    },
    settlement() {
      return this.$store.state.settlement;
    },
    pass() {
      return this.$store.getters.valid_step4;
    },
  },
  mounted() {
    if (this.merchantForm.storeAddressImg) {
      this.storeAddressImgList = [{ url: this.merchantForm.storeAddressImg }];
    }
    if (this.merchantForm.storeDoorImg) {
      this.storeDoorImgList = [{ url: this.merchantForm.storeDoorImg }];
    }
    if (this.merchantForm.cashierImg) {
      this.cashierImgList = [{ url: this.merchantForm.cashierImg }];
    }
    if (this.merchantForm.proofHandImg) {
      this.proofHandImgList = [{ url: this.merchantForm.proofHandImg }];
    }
    if (this.merchantForm.proofImg) {
      this.proofImgList = [{ url: this.merchantForm.proofImg }];
    }
    if (this.merchantForm.assistImg.length > 0) {
      this.assistImgList = this.merchantForm.assistImg;
    }
    let form = this.$store.state.merchant;
    let newForm = JSON.parse(JSON.stringify(form));
    this.formData = newForm;
    this.getChannelTemplateFun();
    window.scrollTo({
      left: 0,
      top: 0,
      behavior: "smooth",
    });
  },
  methods: {
    async isBlackListMethods(val, message) {
      if (!val) return false;
      const { data } = await isBlacklist(val);
      try {
        if (data.isBlacklist) {
          let msg = data.consumerHotline
            ? `${message}填写失败，代码1000，请联系客服${data.consumerHotline}`
            : `${message}填写失败，代码1000`;
          let doms = document.getElementsByClassName("van-toast")[0];
          if (
            doms == undefined ||
            (doms.style && doms.style.display == "none")
          ) {
            this.$toast(msg);
          }
          return true;
        } else {
          return false;
        }
      } catch (error) {
        console.error(error);
        return false;
      }
    },
    goBack() {
      // this.$router.push({
      //   path: "/step3",
      // });
      this.$router.go(-1);
    },
    noSave() {
      this.$dialog
        .confirm({
          title: "商户认证",
          message: `<div style="font-size:16px;line-height:12px;">
                <p>确认是否保存资料？</p> </div>`,
          cancelButtonText: "取消",
          // cancelButtonColor: "#FFB72F",
          confirmButtonText: "确认",
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          // 保存资料
          this.$store.commit("setComplete", 0);
          this.$toast({
            type: "loading",
            message: "正在提交...",
            forbidClick: true,
            duration: 0,
          });
          save(this.$store.state)
            .then((res) => {
              //   document.title = "提交成功";
              this.$toast.clear();
              if (res.code == 200) {
                this.$toast({
                  type: "success",
                  message: "保存成功",
                  duration: 1500,
                });
                this.$store.dispatch("setSaved", true);
              } else {
                this.$toast({
                  message: res.msg || "操作失败",
                  duration: 2000,
                  forbidClick: true,
                });
              }
            })
            .catch((err) => {
              this.$toast.clear();
              document.title = "返回APP";
            });
          // next();
        })
        .catch(() => {
          // 取消
          // document.title = "返回APP";
          // next();
        });
    },
    lookExample(url) {
      this.exampleImg = url;
      this.showExample = true;
    },
    nextStep() {
      Promise.all([
        this.isBlackListMethods(this.userInfo.storeMobile, "手机号"),
        this.isBlackListMethods(this.settlement.settlementNum, "结算人证件号"),
        this.isBlackListMethods(this.merchantForm.legalIdcard, "法人身份证号"),
      ]).then((arr) => {
        if (!arr.some((v) => v == true)) {
          this.$router.push({
            path: "/signature",
          });
        }
      });
    },
    onOversize() {
      this.$toast("图片过大无法上传\n请上传10MB以内的图片！");
    },
    deleteCashierImg(file) {
      this.$dialog
        .alert({
          title: "移除图片",
          message: "是否确定移除该图片？",
          closeOnClickOverlay: true,
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.cashierImgList = [];
          this.$store.commit("PSetCashierImg", "");
        });
    },
    uploadCashierImg(file) {
      file.status = "uploading";
      file.message = "上传中...";
      imgPreview(file.file, (params) => {
        if (!params) {
          file.status = "";
          file.message = "";
          this.cashierImgList = [];
          this.$store.commit("PSetCashierImg", "");
          return;
        }
        uploadImg(params)
          .then((res) => {
            if (res.code == 200) {
              const { link } = res.data;
              file.status = "done";
              this.cashierImgList = [];
              this.cashierImgList.push({ url: link });
              this.$store.commit("PSetCashierImg", link);
            }
          })
          .catch((err) => {
            file.status = "failed";
            file.message = "上传失败";
            this.$toast({
              message: err.msg,
              duration: 2000,
            });
          });
      });
    },
    //法人手持商户关系证明
    uploadProofHandImg(file) {
      file.status = "uploading";
      file.message = "上传中...";
      imgPreview(file.file, (params) => {
        if (!params) {
          file.status = "";
          file.message = "";
          this.proofHandImgList = [];
          this.$store.commit("PSetProofHandImg", "");
          return;
        }
        uploadImg(params)
          .then((res) => {
            if (res.code == 200) {
              const { link } = res.data;
              file.status = "done";
              this.proofHandImgList = [];
              this.proofHandImgList.push({ url: link });
              this.$store.commit("PSetProofHandImg", link);
            }
          })
          .catch((err) => {
            file.status = "failed";
            file.message = "上传失败";
            this.$toast({
              message: err.msg,
              duration: 2000,
            });
          });
      });
    },
    deleteProofHandImg(file) {
      this.$dialog
        .alert({
          title: "移除图片",
          message: "是否确定移除该图片？",
          closeOnClickOverlay: true,
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.proofHandImgList = [];
          this.$store.commit("PSetProofHandImg", "");
        });
    },

    //营业场所照
    deleteStoreAddressImg(file) {
      this.$dialog
        .alert({
          title: "移除图片",
          message: "是否确定移除该图片？",
          closeOnClickOverlay: true,
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.storeAddressImgList = [];
          this.$store.commit("PSetStoreAddressImg", "");
        });
    },
    uploadStoreAddressImg(file) {
      file.status = "uploading";
      file.message = "上传中...";
      imgPreview(file.file, (params) => {
        if (!params) {
          file.status = "";
          file.message = "";
          this.storeAddressImgList = [];
          this.$store.commit("PSetStoreAddressImg", "");
          return;
        }
        uploadImg(params)
          .then((res) => {
            if (res.code == 200) {
              const { link } = res.data;
              file.status = "done";
              this.storeAddressImgList = [];
              this.storeAddressImgList.push({ url: link });
              this.$store.commit("PSetStoreAddressImg", link);
            }
          })
          .catch((err) => {
            file.status = "failed";
            file.message = "上传失败";
            this.$toast({
              message: err.msg,
              duration: 2000,
            });
          });
      });
    },
    //门头照
    deleteStoreDoorImg(file) {
      this.$dialog
        .alert({
          title: "移除图片",
          message: "是否确定移除该图片？",
          closeOnClickOverlay: true,
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.storeDoorImgList = [];
          this.$store.commit("PSetStoreDoorImg", "");
        });
    },
    uploadStoreDoorImg(file) {
      file.status = "uploading";
      file.message = "上传中...";
      imgPreview(file.file, (params) => {
        if (!params) {
          file.status = "";
          file.message = "";
          this.storeDoorImgList = [];
          this.$store.commit("PSetStoreDoorImg", "");
          return;
        }
        uploadImg(params)
          .then((res) => {
            if (res.code == 200) {
              const { link } = res.data;
              file.status = "done";
              this.storeDoorImgList = [];
              this.storeDoorImgList.push({ url: link });
              this.$store.commit("PSetStoreDoorImg", link);
            }
          })
          .catch((err) => {
            file.status = "failed";
            file.message = "上传失败";
            this.$toast({
              message: err.msg,
              duration: 2000,
            });
          });
      });
    },
    //关系证明
    deleteProofImg(file) {
      this.$dialog
        .alert({
          title: "移除图片",
          message: "是否确定移除该图片？",
          closeOnClickOverlay: true,
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.proofImgList = [];
          this.$store.commit("PSetProofImg", "");
        });
    },
    uploadProofImg(file) {
      file.status = "uploading";
      file.message = "上传中...";
      imgPreview(file.file, (params) => {
        if (!params) {
          file.status = "";
          file.message = "";
          this.proofImgList = [];
          this.$store.commit("PSetProofImg", "");
          return;
        }
        uploadImg(params)
          .then((res) => {
            if (res.code == 200) {
              const { link } = res.data;
              file.status = "done";
              this.proofImgList = [];
              this.proofImgList.push({ url: link });
              this.$store.commit("PSetProofImg", link);
            }
          })
          .catch((err) => {
            file.status = "failed";
            file.message = "上传失败";
            this.$toast({
              message: err.msg,
              duration: 2000,
            });
          });
      });
    },
    //辅助材料
    deleteAssistImg(file, detail) {
      this.$dialog
        .alert({
          title: "移除图片",
          message: "是否确定移除该图片？",
          closeOnClickOverlay: true,
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.assistImgList.splice(detail.index, 1);
          this.$store.commit("PRemoveAssistImg", detail.index);
        });
    },
    uploadAssistImg(file, detail) {
      file.status = "uploading";
      file.message = "上传中...";
      imgPreview(file.file, (params) => {
        if (!params) {
          file.status = "";
          file.message = "";
          this.assistImgList.splice(detail.index, 1);
          this.$store.commit("PRemoveAssistImg", detail.index);
          return;
        }
        uploadImg(params)
          .then((res) => {
            if (res.code == 200) {
              const { link } = res.data;
              file.status = "done";
              this.assistImgList.push({ url: link, link: true });
              let ImgList = JSON.parse(JSON.stringify(this.assistImgList));
              let newImgList = [];
              ImgList.forEach((i) => {
                if (i.link) {
                  newImgList.push(i);
                }
              });
              this.assistImgList = newImgList;
              this.$store.commit("PSetAssistImg", link);
            }
          })
          .catch((err) => {
            file.status = "failed";
            file.message = "上传失败";
            this.$toast({
              message: err.msg,
              duration: 2000,
            });
          });
      });
    },
    // 下载模版
    downloadExample() {
      console.log(this.templateUrl);
      if (this.templateUrl) {
        savePicture(this.templateUrl);
      } else {
        this.$toast("模板获取失败，请联系客服");
      }
    },
    getChannelTemplateFun() {
      // 结算类型为非法对私 切开户类型不为
      const [acconutType, openType] = [
        Number(this.settlement.acconutType),
        Number(this.formData.openType),
      ];
      if (acconutType === 3 && openType !== 1) {
        console.log(this.merchantForm.channelCode);
        getChannelTemplate(this.merchantForm.channelCode).then((res) => {
          const { data, code } = res;
          if (code === 200) {
            this.templateUrl = data.relationCertImageUrl;
          } else {
            this.$toast("模板获取失败，请联系客服");
          }
        });
      }
    },
  },
};
</script>
<style scoped lang="less">
.app {
  background: #f9f9f9;
  padding-bottom: 1px;
}
/deep/.van-uploader__preview-image {
  width: 328px;
  height: 218px;
}
img {
  width: 334px;
  height: 218px;
}
.head-top {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99;
}
.conten {
  background: #f9f9f9;
  //   margin-top: 110px;
  .attach-item {
    margin-top: 24px;
    background: #fff;
    padding: 33px 30px;
    p.attach-item-title {
      font-size: 31px;
      font-weight: 400;
      color: #131313;
    }
    .upload-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
      .attach-label {
        width: 45%;
        padding-left: 5px;
        p {
          font-size: 28px;
          font-weight: 400;
          color: #131313;
          margin: 12px 0;
        }
        .example {
          display: flex;
          align-items: center;
          color: #ffb72f;
          justify-content: center;
        }
      }
    }
  }
}
.header-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32px;
  border-bottom: 1px solid #d7d7d7;
  font-size: 36px;
  background: #fff;
  .header-item {
    font-weight: 500;
    color: #131313;
  }
  .header-save {
    color: #ffb72f;
    font-size: 28px;
  }
}
// .header-box {
//   display: flex;
//   align-items: center;
//   justify-content: space-between;
//   padding: 32px;
//   border-bottom: 1px solid #d7d7d7;
//   font-size: 36px;
//   background: #fff;
//   .header-item {
//     font-weight: 500;
//     color: #131313;
//   }
//   .header-save {
//     color: #ffb72f;
//     font-size: 28px;
//   }
// }
.next-step-btn {
  width: 80%;
  margin: 100px auto;
}
.example-img {
  width: 420px;
  height: 270px;
  margin: 57px auto;
}
/deep/.van-dialog__content {
  text-align: center;
  border-bottom: 1px solid #e3e3e3;
}
</style>
